package main

import (
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	"demogo2/models"
)

func main() {
	/*
	if len(os.Getenv("SERVICE_NAME")) > 0 {
		ServiceName = os.Getenv("SERVICE_NAME")
	}
	*/
	RunServer()
}

func RunServer() {
	http.HandleFunc("/demo/hello", HelloServer)
	http.HandleFunc("/user/show", ShowUser)
	err := http.ListenAndServe(":8080",nil)
	if err != nil {
		log.Fatal("Error: ", err)
	}
}

func HelloServer(w http.ResponseWriter, req *http.Request) {
	log.Printf("%s request to %s\n", req.Method, req.RequestURI)
	delay := req.URL.Query().Get("delay")
	if len(delay) > 0 {
		delayNum, _ := strconv.Atoi(delay)
		time.Sleep(time.Duration(delayNum) * time.Millisecond)
	}
	user := models.StructQueryField(1)
	//io.WriteString(w,"hello,world!\n")
	fmt.Fprintf( w,"<h1>Hello, World!</h1>")
	//查询不到用户的话，仍然可以正常显示
	fmt.Fprintf(w, user.Name)
}

func ShowUser(w http.ResponseWriter, req *http.Request) {
	log.Printf("%s request to %s\n", req.Method, req.RequestURI)
	user := models.StructQueryField(2)
	fmt.Fprintf(w, user.Name)
	fmt.Fprintf(w, "<h1>Show User~</h1>")
}



